package com.lancoo.edu.platform.operation.commons.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 * @author pky
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    /**
     * 线程池
     *
     * @return 线程池
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        threadPoolTaskExecutor.setCorePoolSize(5);
        // 等待任务队列数
        threadPoolTaskExecutor.setQueueCapacity(10);
        // 最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(20);
        // 连接超时时长
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 当任务数量超过 MaxPoolSize 和 QueueCapacity 时使用的策略，该策略是又调用任务的线程执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.initialize(); //初始化线程池。
        return threadPoolTaskExecutor;
    }

    /**
     * 拒绝
     *
     * @return 线程池
     */
    @Bean(name = "discardPolicyTaskExecutor")
    public ThreadPoolTaskExecutor discardPolicyTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        threadPoolTaskExecutor.setCorePoolSize(30);
        // 等待任务队列数
        threadPoolTaskExecutor.setQueueCapacity(100);
        // 最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(50);
        // 连接超时时长
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 当任务数量超过 MaxPoolSize 和 QueueCapacity 时使用的策略，该策略是又调用任务的线程执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        // 等待所有任务结束后再关闭线程池
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.initialize(); //初始化线程池。
        return threadPoolTaskExecutor;
    }

    /**
     * 定时任务线程池
     *
     * @return 定时任务线程池
     */
    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(5); // 设置线程池大小
        scheduler.setThreadNamePrefix("scheduled-task-"); // 设置线程名称前缀
        scheduler.setAwaitTerminationSeconds(60); // 设置终止等待时间
        // 设置处理拒绝执行的任务异常
        scheduler.setRejectedExecutionHandler((r, executor) -> log.error("任务拒绝：{}", r));
        // 处理定时任务执行过程中抛出的未捕获异常
        scheduler.setErrorHandler(e -> log.error("定时任务执行异常：", e));
        return scheduler;
    }
}
